package com.pri.chat.activity;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.os.Build;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

import com.google.gson.Gson;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.entity.LocalMedia;
import com.luck.picture.lib.style.PictureWindowAnimationStyle;
import com.netease.nim.uikit.net.SharedHelper;
import com.netease.nim.uikit.net.entity.BaseBean;
import com.netease.nim.uikit.net.rxjava.HttpMethods;
import com.netease.nim.uikit.net.subscribers.ProgressSubscriber;
import com.netease.nim.uikit.net.subscribers.SubscriberOnNextListener;
import com.pri.chat.R;
import com.pri.chat.adapter.GridImageAdapter;
import com.pri.chat.base.BaseActivity;
import com.pri.chat.model.DTMsgModel;
import com.pri.chat.utils.Auth;
import com.pri.chat.utils.Des3Util;
import com.pri.chat.utils.FullyGridLayoutManager;
import com.pri.chat.utils.GlideEngine;
import com.qiniu.android.http.ResponseInfo;
import com.qiniu.android.storage.UpCompletionHandler;
import com.qiniu.android.storage.UpProgressHandler;
import com.qiniu.android.storage.UploadManager;
import com.qiniu.android.storage.UploadOptions;
import com.vondear.rxtool.view.RxToast;
import com.vondear.rxui.view.dialog.RxDialogProgressLoading;

import org.json.JSONObject;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import androidx.annotation.Nullable;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import butterknife.BindView;
import butterknife.OnClick;
import okhttp3.MediaType;
import okhttp3.RequestBody;

/**
 * 描述：添加类的描述
 *
 * @author wx5e48d604c2885118
 * @time 2020/4/8
 */
public class ReleaseVideoActivity extends BaseActivity {
    private static final String TAG = "ReleaseVideoActivity";
    private final static int MAXVALUE = 100;//进度最大值
    @BindView(R.id.et_content)
    EditText etContent;
    @BindView(R.id.rec_img)
    RecyclerView recImg;
    @BindView(R.id.tv_release)
    TextView tvRelease;
    /**
     * 图纸图片
     */
    private GridImageAdapter mPostAdapter;
    private List<LocalMedia> localMediaList = new ArrayList<>();//个人荣誉
    private RxDialogProgressLoading rxDialogLoading;
    private int progressStart = 0;//进度初始值
    /**
     * 更新进度
     */
    @SuppressLint("HandlerLeak")
    final Handler hand = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            //这里的话如果接受到信息码是123
            if (msg.what == 123) {
                //设置进度条的当前值
                rxDialogLoading.getRxRoundProgressBar().setProgress(progressStart);
                rxDialogLoading.getRxRoundProgressBar().setText(progressStart+"%");
                if(progressStart==MAXVALUE){
                    rxDialogLoading.getRxRoundProgressBar().finishLoad();
                }
            }

        }
    };
    private String video_path = "";
    /**
     * 七牛上传视频handler
     */
    private UpCompletionHandler handler = new UpCompletionHandler() {
        @Override
        public void complete(String key, ResponseInfo info, JSONObject response) {
            if (info.isOK()) {
                video_path = HttpMethods.QN_PATH + key;
                rxDialogLoading.dismiss();
                progressStart = 0;
                httpReleaseDT();
                Log.i("qiniuvideo", video_path);
            } else {
                Log.i("qiniu", "Upload Fail");
                //如果失败，这里可以把info信息上报自己的服务器，便于后面分析上传错误原因
            }
        }
    };
    private UploadManager uploadManager = new UploadManager();

    @Override
    protected int getLayoutId() {
        return R.layout.activity_release_video_layout;
    }

    @Override
    protected void initView() {
        setTitle("发布视频");
        btnRight.setVisibility(View.VISIBLE);
        initImg();
        initLoadingDialog();
    }

    private void initImg() {
        FullyGridLayoutManager manager = new FullyGridLayoutManager(this, 3, GridLayoutManager.VERTICAL, false);
        recImg.setLayoutManager(manager);
        mPostAdapter = new GridImageAdapter(this, new GridImageAdapter.onAddPicClickListener() {
            @Override
            public void onAddPicClick() {
                PictureSelector.create(activity)
                        .openGallery(PictureMimeType.ofVideo())//全部.PictureMimeType.ofAll()、图片.ofImage()、视频.ofVideo()、音频.ofAudio()
                        .setPictureWindowAnimationStyle(new PictureWindowAnimationStyle())// 自定义相册启动退出动画
                        .loadImageEngine(GlideEngine.createGlideEngine())// 外部传入图片加载引擎，必传项   参考Demo MainActivity中代码
                        .videoQuality(1)
                        .isWeChatStyle(true)// 是否开启微信图片选择风格，此开关开启了才可使用微信主题！！！
                        .isAndroidQTransform(true)// 是否需要处理Android Q 拷贝至应用沙盒的操作，只针对compress(false); && enableCrop(false);有效
                        .maxSelectNum(1)// 最大图片选择数量 int
                        .minSelectNum(1)// 最小选择数量 int
                        .imageSpanCount(3)// 每行显示个数 int
                        .setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED)
                        .isNotPreviewDownload(true)// 预览图片长按是否可以下载
                        .queryMaxFileSize(1000)// 只查多少M以内的图片、视频、音频  单位M
                        .isSingleDirectReturn(false)// 单选模式下是否直接返回，PictureConfig.SINGLE模式下有效
                        .selectionMode(PictureConfig.MULTIPLE)// 多选 or 单选 PictureConfig.MULTIPLE or PictureConfig.SINGLE
                        .previewImage(true)// 是否可预览图片 true or false
                        .isCamera(true)// 是否显示拍照按钮 true or false
                        .isZoomAnim(true)// 图片列表点击 缩放效果 默认true
                        .sizeMultiplier(0.5f)// glide 加载图片大小 0~1之间 如设置 .glideOverride()无效
                        .setOutputCameraPath("/CustomPath")// 自定义拍照保存路径,可不填
                        .enableCrop(false)// 是否裁剪 true or false
                        .compress(true)// 是否压缩 true or false
                        .isGif(true)// 是否显示gif图片 true or false
                        //   .compressSavePath(getPath())//压缩图片保存地址
                        .openClickSound(false)// 是否开启点击声音 true or false
                        .selectionMedia(localMediaList)// 是否传入已选图片 List<LocalMedia> list
                        .cutOutQuality(90)// 裁剪输出质量 默认100
                        .minimumCompressSize(100)// 小于100kb的图片不压缩
                        .videoMaxSecond(300)
                        .videoMinSecond(5)
                        .recordVideoSecond(20)
                        .forResult(PictureConfig.CHOOSE_REQUEST);//结果回调onActivityResult code
            }
        });
        mPostAdapter.setList(localMediaList);
        mPostAdapter.setSelectMax(1);
        recImg.setAdapter(mPostAdapter);
            mPostAdapter.setOnItemClickListener((position, v) ->
                PictureSelector.create(this)
                        .themeStyle(R.style.picture_default_style)
                        .loadImageEngine(GlideEngine.createGlideEngine())// 外部传入图片加载引擎，必传项
                        .openExternalPreview(position, localMediaList));
    }

    private void initLoadingDialog() {
        rxDialogLoading = new RxDialogProgressLoading(this);
        rxDialogLoading.getRxRoundProgressBar().setText("0%");
        rxDialogLoading.setCancelable(false);//设置是否可取消
    }

    @Override
    protected void initData() {
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            case PictureConfig.CHOOSE_REQUEST:
                // 图片选择结果回调
                if (!PictureSelector.obtainMultipleResult(data).isEmpty()) {
                    localMediaList.clear();
                    localMediaList.addAll(PictureSelector.obtainMultipleResult(data));
                    mPostAdapter.notifyDataSetChanged();
                }
                break;
        }
    }

    @OnClick(R.id.tv_release)
    public void onViewClicked() {
        if (isNull(etContent)) {
            RxToast.normal("请输入需要分享的内容");
            return;
        }
        if (!localMediaList.isEmpty()) {
            rxDialogLoading.show();
            if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
                uploadVideo(localMediaList.get(0).getAndroidQToPath());
            }else{
                uploadVideo(localMediaList.get(0).getPath());
            }
        } else {
            httpReleaseDT();
        }
    }

    /**
     * 上传视频
     * @param compressPath 视频本地路径
     */
    private void uploadVideo(String compressPath) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
        File file = new File(compressPath);
        String key = "video_" + sdf.format(new Date());
        String token = "ayjstx";
        uploadManager.put(compressPath, key, Auth.create(HttpMethods.ACCESS_KEY, HttpMethods.SECRET_KEY).uploadToken(token), handler,
                new UploadOptions(null, null, false,
                        new UpProgressHandler() {
                            public void progress(String key, final double percent) {
                                Log.i("qiniu", key + ": " + percent);
                                //这里的算法是决定进度条变化的,可以按需要写
                                progressStart = (int) (((float) percent) * 100);
                                Log.i("qiniu1", progressStart + ": " + percent);
                                //把信息码发送给handle让更新界面
                                hand.sendEmptyMessage(123);

                            }
                        }, null));

    }

    /**
     * 发布视频动态
     */
    private void httpReleaseDT() {
        SubscriberOnNextListener<BaseBean> onNextListener = baseBean -> {
            Log.d(TAG, "onNext: " + baseBean.toString());
            RxToast.normal("发布成功");
            setResult(0x10);
            finish();

        };
        DTMsgModel dtMsgModel = new DTMsgModel();
        dtMsgModel.setContent(getString(etContent));
        dtMsgModel.setType(1);
        dtMsgModel.setMemberId(SharedHelper.readId(this));
        dtMsgModel.setVideoPath(video_path);
        RequestBody requestBody = RequestBody.create(MediaType.parse("application/json;charset=utf-8"), Des3Util.getJiaMi(dtMsgModel));
        HttpMethods.getInstance().createDynamic(new ProgressSubscriber<>(onNextListener, this, true), requestBody);
    }
}
